import { Injectable, Logger } from '@nestjs/common';
import axios from 'axios';
import * as cheerio from 'cheerio';
const nodeXlsx = require('node-xlsx');
const fs = require('fs');
const moment = require('moment');

@Injectable()
export default class GetMaoTai {
  private readonly url: string =
    'http://quotes.money.163.com/f10/zycwzb_600519.html#01c01';
  private readonly logger = new Logger();

  async getProduct() {
    const res = await axios.get(this.url);
    // console.log(res);
    const $ = cheerio.load(res.data);
    const tdStr = $('.col_r .table_bg001  tbody tr:nth-child(12)').html();
    const reg = /<td[\S\s]*?>([\S\s]*?)<\/td>/gi;
    const result = [];
    let a;
    while ((a = reg.exec(tdStr)) != null) {
      result.push(a[1].replace('\n', ''));
    }
    console.log(result);
    let data = [];
    const title = ['净利润(扣除非经常性损益后)(万元)'];

    data = [title, result];
    console.log(title[0]);
    this.writeExcel(title[0] + this.GetDateStr(), data);
    return;
  }

  writeExcel(name, data) {
    console.log(name);

    const buffer = nodeXlsx.build([{ name: 'sheet1', data: data }]);
    fs.writeFileSync(name + '.xlsx', buffer, { flag: 'w' });
  }
  GetDateStr() {
    return moment().format('YYYY-MM-DD');
  }
}
